from markdown import markdown

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

def extractCode(text):
    lines = text.split('\n')
    codeSnippits = []
    codeLessMarkedText = ''
    #loop over every single line in the text
    i = -1
    while i < (len(lines) - 1):
        i = i + 1 # should start at zero
        if lines[i].find('!@#') == 0:
            #we have found the start of a code snipit
            codeLessMarkedText += '!@##@!' + '\n'
            codeSnip = lines[i] + '\n'
            while i < (len(lines) - 1):
                i = i + 1
                if lines[i].find('!@#') == 0:
                    break
                codeSnip += lines[i] + '\n'
            codeSnippits.append(codeSnip)
        else:
            codeLessMarkedText += lines[i] + '\n'
    return codeSnippits, codeLessMarkedText


def render(newBlogMarkdown):
    # first extract all code snipits and replace with markers
    codeSnippits, markedCodelessText = extractCode(newBlogMarkdown)
    markDownText = markdown.markdown(markedCodelessText)
    
    for codeSnip in codeSnippits:
        # we need to html format, then replace
        try:
            codeLines = codeSnip.split('\n')
            firstLine = codeLines[0]
            codeLines = codeLines[1:]
            codeSnip = codeSnip[codeSnip.find('\n') + 1 :]
            lexType = firstLine[4:].strip()
            lexer = get_lexer_by_name(lexType, stripall=True)
            formatter = HtmlFormatter(linenos=True)
            result = highlight(codeSnip, lexer, formatter)
            result = '<div class="codeSurround">' + result + '</div>'
        #print 'results is: ' + result
        except:
            result = codeSnip
        markDownText = markDownText.replace('!@##@!', result, 1)
    
    return markDownText